package com.gitee.wsl.common.chart.render.background.axis.format

import com.gitee.wsl.transform.format.Format
import java.text.DecimalFormat

/**
 * Predefined value-formatter that formats large numbers in a pretty way.
 * Outputs: 856 = 856; 1000 = 1k; 5821 = 5.8k; 10500 = 10k; 101800 = 102k;
 * 2000000 = 2m; 7800000 = 7.8m; 92150000 = 92m; 123200000 = 123m; 9999999 =
 * 10m; 1000000000 = 1b; Special thanks to Roman Gromov
 * (https://github.com/romangromov) for this piece of code.
 *
 * @author Philipp Jahoda
 * @author Oleksandr Tyshkovets <olexandr.tyshkovets></olexandr.tyshkovets>@gmail.com>
 */
class LargeFormatter(var appendix: String = "") : Format<Float> {
    var suffix = arrayOf(
        "", "k", "m", "b", "t"
    )
    var maxLength = 5
    val format: DecimalFormat = DecimalFormat("###E00")


    /**
     * Formats each number properly. Special thanks to Roman Gromov
     * (https://github.com/romangromov) for this piece of code.
     */
    private fun makePretty(number: Double): String {
        var r = format.format(number)
        val numericValue1 = Character.getNumericValue(r[r.length - 1])
        val numericValue2 = Character.getNumericValue(r[r.length - 2])
        val combined = Integer.valueOf(numericValue2.toString() + "" + numericValue1)
        r = r.replace("E[0-9][0-9]".toRegex(), suffix[combined / 3])
        while (r.length > maxLength || r.matches("[0-9]+\\.[a-z]".toRegex())) {
            r = r.substring(0, r.length - 2) + r.substring(r.length - 1)
        }
        return r
    }

    val decimalDigits: Int
        get() = 0

    override fun format(value: Float): String {
        return makePretty(value.toDouble()) + appendix
    }


}